﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace Kocic.RepositoryManagement
{
    /// <summary>
    /// Generic object factory.
    /// </summary>
    public static class ObjectFactory
    {
        /// <summary>
        /// Creates an instance of an object of type T.
        /// </summary>
        /// <typeparam name="T">Type of the object to create.</typeparam>
        /// <param name="paramList">Constructor parameter list.</param>
        /// <returns>Instance of type T.</returns>
        public static T Create<T>(params Object[] paramList)
            where T: class, new()
        {
            if (paramList == null)
            {
                return new T();
            }
            else
            {
                Type t = typeof(T);

                ConstructorInfo reportConstructor = t.GetConstructor(paramList.Select(p => p.GetType()).ToArray());
                object reportClassObject = reportConstructor.Invoke(paramList);

                return (reportClassObject as T);
            }
        }

        /// <summary>
        /// Creates an instance of an object of type T.
        /// </summary>
        /// <typeparam name="T">Type of the object to create.</typeparam>
        /// <param name="createdObjectCallback">Callback method to be used with created object.</param>
        /// <param name="paramList">Constructor parameter list.</param>
        public static void Create<T>(Action<T> createdObjectCallback, params Object[] paramList)
            where T : class, new()
        {
            T createdObject = ObjectFactory.Create<T>(paramList);
            createdObjectCallback(createdObject);
        }
    }
}
